const mongoose = require('mongoose');
const ObjectId = mongoose.Types.ObjectId;
const { User, GroupNotification, groupChat } = require('../../../models');

// 获取群通知
async function getGroupNotifications(io, socket, data, callback) {
    try {
        const user = await User.findOne({ phone: data.phone });
        if (!user) {
            return callback({ code: 404, message: '用户不存在' });
        }

        // 查询用户的群通知
        const notifications = await GroupNotification.find({ recipient: user._id })
            .populate('groupId', 'groupName groupAvatar')
            .populate('inviterId', 'nickname headImgUrl')
            .sort({ createTime: -1 })
            .skip((data.page - 1) * data.pageSize)
            .limit(data.pageSize);

        // 为前端处理数据格式
        const formattedNotifications = notifications.map(notification => {
            return {
                _id: notification._id,
                groupName: notification.groupId.groupName,
                groupAvatar: notification.groupId.groupAvatar,
                inviterName: notification.inviterId ? notification.inviterId.nickname : '系统',
                type: notification.type,
                content: notification.content,
                status: notification.status,
                createTime: notification.createTime,
                isRead: notification.isRead
            };
        });

        // 更新通知为已读
        await GroupNotification.updateMany(
            { recipient: user._id, isRead: false },
            { isRead: true }
        );

        // 发送socket事件通知前端更新未读状态
        io.to(socket.id).emit('updateGroupNotificationCount', { hasUnread: false });

        return callback({ 
            code: 200, 
            message: '获取群通知成功', 
            notifications: formattedNotifications 
        });
    } catch (error) {
        console.error('获取群通知失败:', error);
        return callback({ code: 500, message: '获取群通知失败: ' + error.message });
    }
}

// 处理群邀请
async function handleGroupInvitation(io, socket, data, callback) {
    try {
        const user = await User.findOne({ phone: data.phone });
        if (!user) {
            return callback({ code: 404, message: '用户不存在' });
        }

        // 查找通知
        const notification = await GroupNotification.findById(data.notificationId);
        if (!notification) {
            return callback({ code: 404, message: '通知不存在' });
        }

        // 验证通知是否属于该用户
        if (notification.recipient.toString() !== user._id.toString()) {
            return callback({ code: 403, message: '无权操作此通知' });
        }

        // 如果通知不是待处理状态
        if (notification.status !== 'pending') {
            return callback({ code: 400, message: '此通知已被处理' });
        }

        // 查找群聊
        const group = await groupChat.findById(notification.groupId);
        if (!group) {
            notification.status = 'expired';
            await notification.save();
            return callback({ code: 404, message: '群聊不存在或已被删除' });
        }

        // 根据操作更新通知状态
        if (data.action === 'accept') {
            // 接受邀请，将用户添加到群成员中
            if (!group.members.includes(user._id)) {
                group.members.push(user._id);
                await group.save();
            }

            // 将群添加到用户的加入群列表
            if (!user.joinedGroups.includes(group._id)) {
                user.joinedGroups.push(group._id);
                await user.save();
            }

            notification.status = 'accepted';
            await notification.save();

            // 向群中广播新成员加入的消息
            io.to(`group_${group._id}`).emit('newMemberJoined', {
                groupId: group._id,
                userId: user._id,
                nickname: user.nickname
            });

            return callback({ code: 200, message: '已成功加入群聊' });
        } else if (data.action === 'reject') {
            // 拒绝邀请
            notification.status = 'rejected';
            await notification.save();
            return callback({ code: 200, message: '已拒绝邀请' });
        } else {
            return callback({ code: 400, message: '无效的操作' });
        }
    } catch (error) {
        console.error('处理群邀请失败:', error);
        return callback({ code: 500, message: '处理群邀请失败: ' + error.message });
    }
}

// 创建群邀请通知
async function createGroupInvitation(io, socket, data, callback) {
    try {
        const inviter = await User.findOne({ phone: data.inviterPhone });
        if (!inviter) {
            return callback({ code: 404, message: '邀请者不存在' });
        }

        // 查找群聊
        const group = await groupChat.findById(data.groupId);
        if (!group) {
            return callback({ code: 404, message: '群聊不存在' });
        }

        // 验证邀请者是否是群成员
        if (!group.members.includes(inviter._id)) {
            return callback({ code: 403, message: '您不是该群成员，无法邀请他人' });
        }

        // 创建通知对象
        const notificationData = {
            recipient: data.userId,
            groupId: group._id,
            type: 'invitation',
            inviterId: inviter._id,
            content: `${inviter.nickname}邀请您加入群聊"${group.groupName}"`,
            status: 'pending'
        };

        const notification = await GroupNotification.create(notificationData);

        // 查找被邀请者
        const recipient = await User.findById(data.userId);
        if (recipient && recipient.socketId) {
            // 向被邀请者发送新通知
            const formattedNotification = {
                _id: notification._id,
                groupName: group.groupName,
                groupAvatar: group.groupAvatar,
                inviterName: inviter.nickname,
                type: notification.type,
                content: notification.content,
                status: notification.status,
                createTime: notification.createTime,
                isRead: notification.isRead
            };

            io.to(recipient.socketId).emit('newGroupNotification', formattedNotification);
            io.to(recipient.socketId).emit('updateGroupNotificationCount', { hasUnread: true });
        }

        return callback({ code: 200, message: '邀请已发送' });
    } catch (error) {
        console.error('创建群邀请失败:', error);
        return callback({ code: 500, message: '创建群邀请失败: ' + error.message });
    }
}

// 检查是否有未读群通知
async function checkUnreadGroupNotifications(io, socket, data, callback) {
    try {
        const user = await User.findOne({ phone: data.phone });
        if (!user) {
            return callback({ code: 404, message: '用户不存在' });
        }

        // 查询用户是否有未读群通知
        const unreadCount = await GroupNotification.countDocuments({ 
            recipient: user._id,
            isRead: false 
        });

        return callback({ 
            code: 200, 
            hasUnread: unreadCount > 0 
        });
    } catch (error) {
        console.error('检查未读群通知失败:', error);
        return callback({ code: 500, message: '检查未读群通知失败: ' + error.message });
    }
}

module.exports = {
    getGroupNotifications,
    handleGroupInvitation,
    createGroupInvitation,
    checkUnreadGroupNotifications
}; 